<?php

class Rcp_Methods_Request_GetCalendarEvents {
	
	const DEFAULT_START_TIME = '0:00';
	const DEFAULT_END_TIME = '23:59';
	
	/**
	 *
	 * @var Rcp_Methods_Data_App
	 */
	public $app;
	public $userId;
	public $range;
	
	public function __construct($params) {
		$this->app = new Rcp_Methods_Data_App($params->app);
		$this->userId = ($params->userId == null) ? Rcp_Auth::getInstance()->getUser()->getId() : $params->userId;
		$this->range = new Rcp_Methods_Data_DateRange($params->range);
	}
	
	public function process() {
		$calendarEvents = RcpCalendarEventsQuery::create()
		->filterByActive(true)
		->filterByUserId($this->userId)
		->filterByDate($this->range->from->format('Y-m-d'), Criteria::GREATER_EQUAL)
		->filterByDate($this->range->to->format('Y-m-d'), Criteria::LESS_EQUAL)
		->find();
		
		$response = new Rcp_Methods_Response_GetCalendarEvents();
		
		foreach ($calendarEvents as $event) {
			if (!($event instanceof RcpCalendarEvents))
				continue;
			$this->setNullTime($calendarEvents, $event);				
			$response->calendarEvents[] = new Rcp_Methods_Data_CalendarEvent($event);
		}
		
		return $response;
	}
	
	private function setNullTime($calendarEvents, RcpCalendarEvents $event) {
		if ($event->getStartDate() === null) {
			$startDate = null;
			foreach ($calendarEvents as $calendarEvent) {
				if ($calendarEvent->getDate() !== $event->getDate())
					continue;
				if ($calendarEvent->getEndDate(null) < $event->getEndDate(null) && ($startDate == null || $startDate > $calendarEvent->getEndDate(null)))
					$startDate = $calendarEvent->getEndDate(null);
			}
			$event->setStartDate(($startDate === null) ? new DateTime($event->getDate() . ' ' . self::DEFAULT_START_TIME) : $startDate);
		}
		if ($event->getEndDate() === null) {
			$endDate = null;
			foreach ($calendarEvents as $calendarEvent) {
				if ($calendarEvent->getDate() !== $event->getDate())
					continue;
				if ($calendarEvent->getStartDate(null) > $event->getStartDate(null) && ($endDate == null || $endDate < $calendarEvent->getStartDate(null)))
					$endDate = $calendarEvent->getStartDate(null);
			}
			$event->setEndDate(($endDate === null) ? new DateTime($event->getDate() . ' ' . self::DEFAULT_END_TIME) : $endDate);
		}
	}
	
	private function getOverTimeEvent(RcpCalendarEvents $event) {
		$event->getEndDate();
	}
	
}